package Server;

import Server.Database.Database;
import java.io.IOException;
import java.net.ServerSocket;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Timer;

/**
 * Main class of Server package. Used to start the ServerSocket, Database, 
 * @author PZK
 *
 */
public class Server extends Thread {

	public static final int PORT = 3306;//12345;
	public static final String DATABASE_URL = //"jdbc:mysql://sql2.freemysqlhosting.net";
        "jdbc:mysql://db4free.net"; 
	public static final String DATABASE_USERNAME = //"sql27343";
        "pineapple";//= "root";
	public static final String DATABASE_PASSWORD = //"xC9*yU4%";
        "pineapple";//= "";
	private ServerSocket serverSocket;
	private Database database;
        public Timer timer = null;
        public Timer timer2 = null;
        public Boolean stopServer = false;
       // public Timer timer;
	@SuppressWarnings("unused")
	private ClientHandler clientHandler; //for future reference.

	public Server() {
        //public void run(){
		try {
                        serverSocket = new ServerSocket(12345);
                        //serverSocket.setSoTimeout(30);
		} catch (IOException e) {
                        System.out.println("Serverio klaida");
			e.printStackTrace();
			System.exit(1);
		} catch (IllegalArgumentException e) {
                        System.out.println("Serverio klaida");
			e.printStackTrace();
			System.exit(1);
		}

		try {
			database = new Database(DATABASE_URL+":"+PORT+"/"+DATABASE_USERNAME, DATABASE_USERNAME,
					DATABASE_PASSWORD);
                        
		} catch (SQLException e) {
		
			System.out.println("SQLException: " + e.getMessage());
		    System.out.println("SQLState: " + e.getSQLState());
		    System.out.println("VendorError: " + e.getErrorCode());
			System.out.println("HINT: Turn on the MySQL server..");
			System.exit(1);
		} catch (ClassNotFoundException e) {
			System.out.println("ERROR: MySQL driver for java connector is not installed to the library!");
			System.exit(1);
		}
                int restartTime = 0;
                try {
                    String tempRT = database.settingsRegister.getSettingValue("RESTART");
                    if (!tempRT.equals("")) {
                        restartTime = Integer.parseInt(tempRT);
                    }
                } catch (SQLException ex) {
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                }
                if (restartTime > 0) {
                    timer = new Timer();
                    TimerTask timerTask  = new TimerTask() {
                        public void run() {
                            try {
                                serverSocket.close();
                                System.out.println("Socket Server Closed.");
                                System.out.println("Restarting server.");
                                new Server();
                            } catch (IOException ex) {
                                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    };
                    timer.schedule(timerTask, 60*1000*restartTime);
                }
                
                String shutdownTime = "";
                try {                
                    shutdownTime = database.settingsRegister.getSettingValue("SHUTDOWN");
                } catch (SQLException ex) {
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                timer2 = new Timer();
                TimerTask timerTask2  = new TimerTask() {
                    public void run() {
                        DateFormat dateFormat = new SimpleDateFormat("HH:mm");
                        Date date = new Date();
                        String time = "";
                        try {
                            time = database.settingsRegister.getSettingValue("SHUTDOWN");
                        } catch (SQLException ex) {
                            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        if (time.equals(dateFormat.format(date))) {
                            try {
                                serverSocket.close();
                                System.out.println("Socket Server Closed.");
                                System.out.println("Shutting down server.");
                                System.exit(0);
                            } catch (IOException ex) {
                                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                };
                timer2.schedule(timerTask2, 5000, 30000);
		clientHandler = new ClientHandler(serverSocket, database);
	}

	public static void main(String[] args) {
                new Server();
	}
}
